from datetime import datetime
from marshmallow import Schema, fields
from app.extensions import db

class Node(db.Model):
    __tablename__ = 'nodes'

    id = db.Column(db.Integer, primary_key=True)
    chart_id = db.Column(db.Integer, db.ForeignKey('charts.id'), nullable=False)
    name = db.Column(db.String(100), nullable=False)
    type = db.Column(db.String(50), default='industry')
    description = db.Column(db.Text)
    position_x = db.Column(db.Numeric(10, 2), default=0)
    position_y = db.Column(db.Numeric(10, 2), default=0)
    color = db.Column(db.String(20), default='#409EFF')
    size = db.Column(db.Integer, default=50)
    status = db.Column(db.Enum('active', 'inactive'), default='active')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    upstream_relationships = db.relationship('Relationship',
                                           foreign_keys='Relationship.downstream_node_id',
                                           backref='downstream_node',
                                           cascade='all, delete-orphan')
    downstream_relationships = db.relationship('Relationship',
                                             foreign_keys='Relationship.upstream_node_id',
                                             backref='upstream_node',
                                             cascade='all, delete-orphan')

    def to_dict(self):
        return {
            'id': self.id,
            'chart_id': self.chart_id,
            'name': self.name,
            'type': self.type,
            'description': self.description,
            'position_x': float(self.position_x) if self.position_x else 0,
            'position_y': float(self.position_y) if self.position_y else 0,
            'color': self.color,
            'size': self.size,
            'status': self.status
        }

class NodeSchema(Schema):
    id = fields.Int(dump_only=True)
    chart_id = fields.Int(required=True)
    name = fields.Str(required=True)
    type = fields.Str()
    description = fields.Str()
    position_x = fields.Float()
    position_y = fields.Float()
    color = fields.Str()
    size = fields.Int()
    status = fields.Str()